using DocumentBuilderServer.Dtos;
using DocumentBuilderServer.Infrastructures;
using JMS.Token;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebSocketUploadFile;

namespace DocumentBuilderServer.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class DocController : ControllerBase
    {
        SysDBContext _sysDBContext;
        TokenClient _tokenClient;
        IUploadFileHandler _uploadFileHandler;
        IConfiguration _configuration;
        public DocController(IConfiguration configuration, SysDBContext sysDBContext, IUploadFileHandler uploadFileHandler, TokenClient tokenClient)
        {
            this._sysDBContext = sysDBContext;
            this._tokenClient = tokenClient;
            this._uploadFileHandler = uploadFileHandler;
            this._configuration = configuration;

        }

        [HttpGet]
        public async Task<Category[]> GetDocuments()
        {
            var categories = await (from m in _sysDBContext.Category
                                    orderby m.Sort
                                    select new Dtos.Category {
                                        Caption = m.Caption,
                                        Id = m.id.Value,
                                        Sort = m.Sort,
                                        Documents = _sysDBContext.Doc.Where(n => n.CategoryId == m.id).OrderBy(n => n.Sort).Select(n=>new Document {
                                            Id = n.id.Value,
                                            Caption = n.Caption,
                                            Sort = n.Sort,
                                            Version = n.Version
                                        }).ToArray()
                                    }).ToArrayAsync();

            return categories;
        }

        [HttpGet]
        public string GetImagePath(int tranId)
        {
            return ((UploadHandler)_uploadFileHandler).UploadingDict[tranId].Path;
        }

        [HttpPost]
        public string Login([FromBody] UserInfo userInfo)
        {
            if(string.IsNullOrWhiteSpace(userInfo.Name) || string.IsNullOrWhiteSpace(userInfo.Password))
            {
                Response.StatusCode = 404;
                return "";
            }

            var user = _configuration.GetSection("User").Get<UserInfo>();
            if(user.Name != userInfo.Name || user.Password != userInfo.Password)
            {
                Response.StatusCode = 401;
                return "";
            }

            var token = _tokenClient.Build(user.Name, DateTime.Now.AddHours(1));

            return token;
        }
    }
}